Q. is there a simple way to extract the index of a particular value in a tensor?

A. Lets work this out.

Let's define a tensor with 10 integers from 1 to 10 randomly permuted.


In [3]:
t=torch.randperm(10)

In [4]:
t


Out[4]:
  8
  3
  6
  1
  5
  7
  4
  9
 10
  2
[torch.DoubleTensor of dimension 10]

Now, find all instances of "7" in the tensor.

Let us do two methods.

Method (1) is a simple for-loop.


In [5]:
for i=1,t:size(1) do 
    if t[i] == 7 then
        print('Found 7 at location: ' .. i)
    end
end


Out[5]:
Found 7 at location: 6	

Method (2) which is more efficient and faster:

We use the :eq function, which is part of the logical operators.

https://github.com/torch/torch7/blob/master/doc/maths.md#logical-operations-on-tensors


In [6]:
t:eq(7)


Out[6]:
 0
 0
 0
 0
 0
 1
 0
 0
 0
 0
[torch.ByteTensor of dimension 10]

As you see, it retured a mask, where there is a value 1 wherever there was the value 7. Now, let us extract a new tensor with just the value.


In [7]:
t[t:eq(7)]


Out[7]:
 7
[torch.DoubleTensor of dimension 1]

Okay, but let's say you actually want the Index number of all locations of 7. You can technically do this with a linspace:


In [8]:
idx = torch.linspace(1,t:size(1), t:size(1))

In [9]:
idx[t:eq(7)]


Out[9]:
 6
[torch.DoubleTensor of dimension 1]

Hope this helps make it clear.


In [ ]: